<template>
  <el-dialog v-model="visible" title="信息发送" :destroy-on-close="true" width="500px" draggable>
    <el-form
      ref="ruleFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :model="formData"
      @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="DTU设备编号" prop="dtuNumber">
        <el-input v-model="formData.dtuNumber" disabled></el-input>
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input v-model="formData.name" disabled></el-input>
      </el-form-item>
      <el-form-item label="发送数据" prop="decimal">
        <el-input-number 
          v-model="formData.decimal" 
          :min="0" 
          :max="65535" 
          controls-position="right" 
          placeholder="请输入信息数据"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"> 发送</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { type ElForm, ElMessage } from 'element-plus';
import http from '@/api';
import { ADMIN_MODULE } from '@/api/helper/prefix';

defineOptions({
  name: 'SendDataForm'
});

// 定义发送数据的类型
interface SendDataForm {
  dtuId: number | string;
  decimal: number;
}

interface DtuInfo {
  id: number | string;
  dtuNumber: string;
  name: string;
}

const visible = ref(false);
const loading = ref(false);
const ruleFormRef = ref<InstanceType<typeof ElForm>>();

const formData = reactive({
  dtuId: '' as string | number,
  dtuNumber: '',
  name: '',
  decimal: 30 // 默认值
});

const rules = reactive({
  decimal: [{ required: true, message: '请输入信息' }]
});

// 接收父组件传过来的参数
const acceptParams = (params: DtuInfo) => {
  formData.dtuId = params.id;
  formData.dtuNumber = params.dtuNumber || '';
  formData.name = params.name || '';
  visible.value = true;
};

// 发送数据
const sendDataApi = (params: SendDataForm) => {
  return http.post(ADMIN_MODULE + `/dtu-info/send-data`, params);
};

// 提交数据
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      loading.value = true;
      await sendDataApi({
        dtuId: formData.dtuId,
        decimal: formData.decimal
      });
      ElMessage.success({ message: '信息发送成功！' });
      visible.value = false;
    } catch (error) {
      console.log(error);
      ElMessage.error({ message: '信息发送失败！' });
    } finally {
      loading.value = false;
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss"></style>